import React from 'react';
import routes from './routes';
import PropTypes from 'prop-types';
import {Button, Form, Row, Col, Modal, Card} from 'antd';
const FormItem = Form.Item;
import TextInput from 'Shared/components/TextInput';
import {PERMISSIONS} from './constants';
import {hasPermissions} from './utils';
import {FORM_OPTIONS} from '../constants';
import {injectIntl} from './intl';
import WrappedSelect from '../common/WrappedSelect';
import DealerSelectPanel from '../common/DealerSelect/SelectEdit';
import DateRangePicker from 'Shared/components/DateRangePicker';
import Export from '../common/Export';
import DealerTable from './DealerTable';
import DealerTree from './DealerTree';
import styles from './style.css';
import {getDealersQuickly} from './api';

const ButtonGroup = Button.Group;

class QueryPanel extends React.PureComponent {
    state = {
        data: {},
        loading: false,
        showDealerSelectPanel: false,
    }

    handleFilterChange = (value, name) => {
        this.props.onChange(name, value);
    }

    handleFilterPressEnter = (value, name) => {
        this.props.onChange(name, value);
        this.props.querySearch();
    }
    
    dealerLabelMap = d => {
        if(d.id === undefined)
            return '';
        if(d)
            return `(${d.code}) ${d.name}`;
        return '';
    }

    onSearchDealer = value =>
        getDealersQuickly({filter: value})
            .then(res => {
                const data = res.data;
                if(data)
                    return data.content;
            })
        
    onSelectDealer = data => {
        this.props.onChange('dealerId', data.id);
        this.props.saveDealer({
            id: data.id,
            dealerCode: data.code,
            name: data.name,
        });
        this.setState({
            showDealerSelectPanel: false
        });
    }

    onQueryReset =() => {
        this.props.onClickReset();
    }

    onClickSearchDealerBtn = () => {
        this.setState({showDealerSelectPanel: true});
    }

    onCloseDealerSelectPanel= () => {
        this.setState({showDealerSelectPanel: false});
    }

    render() {
        const {formatMessage} = this.props.intl;
        const condition = this.props.condition || {};
        const dealerInfo = condition.id ? {
            id: condition.id,
            code: condition.dealerCode,
            name: condition.name
        } : null;
        const operations = [];
        const otherBtns = [];
        if(hasPermissions(this.props.permissions, PERMISSIONS.export))
            otherBtns.push(
                <Export key={PERMISSIONS.export} exportRequest={this.props.exportData} />
            );
        if(hasPermissions(this.props.permissions, PERMISSIONS.register))
            operations.push(
                <Button key="register" type="primary" href={`#${routes.register.url()}`}>
                    {this.props.intl.formatMessage({
                        id: 'queryPanel.btn.register',
                        defaultMessage: '登记'
                    })}
                </Button>
            );
        return (
            <div>
                <Form className="form-standard">
                    <Row>
                        {this.props.isDealerUser ? null
                            : <Col {...FORM_OPTIONS.col}>
                                <FormItem label={formatMessage({
                                    id: 'queryPanel.form.dealerCode',
                                    defaultMessage: '总代编号'
                                })} {...FORM_OPTIONS.item}>
                                    <DealerSelectPanel
                                        value={dealerInfo}
                                        onSelect={this.onSelectDealer} />
                                   
                                </FormItem>
                            </Col> }
                        <Col {...FORM_OPTIONS.col}>
                            <FormItem
                                label={this.props.intl.formatMessage({
                                    id: 'queryPanel.form.brand',
                                    defaultMessage: '品牌'
                                })}
                                {...FORM_OPTIONS.item}>
                                <WrappedSelect
                                    allowClear
                                    name="brandId"
                                    value={this.props.condition.brandId}
                                    options={this.props.brands}
                                    onChange={this.handleFilterChange}/>
                            </FormItem>
                        </Col>
                        <Col {...FORM_OPTIONS.col}>
                            <FormItem label={formatMessage({
                                id: 'queryPanel.form.code',
                                defaultMessage: '信用证号码'
                            })}{...FORM_OPTIONS.item}>
                                <TextInput
                                    name="code"
                                    value={this.props.condition.code}
                                    onPressEnter={this.handleFilterPressEnter}
                                    onBlur={this.handleFilterChange} />
                            </FormItem>
                        </Col>
                        <Col {...FORM_OPTIONS.col}>
                            <FormItem label={formatMessage({
                                id: 'queryPanel.form.issueDate',
                                defaultMessage: '开证日期'
                            })} {...FORM_OPTIONS.item}>
                                <DateRangePicker
                                    id="issueDate"
                                    value={this.props.condition.issueDate}
                                    onChange={this.handleFilterChange} />
                            </FormItem>
                        </Col>
                        <Col {...FORM_OPTIONS.col}>
                            <FormItem label={formatMessage({
                                id: 'queryPanel.form.issueBank',
                                defaultMessage: '开证银行'
                            })} {...FORM_OPTIONS.item}>
                                <TextInput
                                    name="issueBank"
                                    value={this.props.condition.issueBank}
                                    onPressEnter={this.handleFilterPressEnter}
                                    onBlur={this.handleFilterChange} />
                            </FormItem>
                        </Col>
                        <Col {...FORM_OPTIONS.col}>
                            <FormItem label={formatMessage({
                                id: 'queryPanel.form.sendBank',
                                defaultMessage: '寄出银行'
                            })} {...FORM_OPTIONS.item}>
                                <TextInput
                                    name="sendBank"
                                    value={this.props.condition.sendBank}
                                    onPressEnter={this.handleFilterPressEnter}
                                    onBlur={this.handleFilterChange} />
                            </FormItem>
                        </Col>
                    </Row>
                    <Row>
                        <Col span={6}>
                            <Button key="query" type="primary"
                                onClick={this.props.querySearch} loading={this.props.loading}>
                                {formatMessage({
                                    id: 'queryPanel.btn.search',
                                    defaultMessage: '查询'
                                })}</Button>
                            <Button key="clear" onClick={this.onQueryReset}>{formatMessage({
                                id: 'queryPanel.btn.reset',
                                defaultMessage: '重置'
                            })}</Button>
                        </Col>
                        <Col span={18} className="col-align-right">
                            {operations}
                            <ButtonGroup>{otherBtns}</ButtonGroup>
                        </Col>
                    </Row>
                </Form>
                <Modal
                    title={formatMessage({
                        id: 'dealer.dealers.modal.item.title',
                        defaultMessage: '总代子公司查询'
                    })}
                    width="80%"
                    maskClosable={false}
                    footer={null}
                    wrapClassName={styles.dataSelectModal}
                    destroyOnClose={true}
                    visible={this.state.showDealerSelectPanel}
                    onCancel={this.onCloseDealerSelectPanel}>
                    <Row gutter={8}>
                        <Col md={8} xl={8} xxl={6}><DealerTree /></Col>
                        <Col md={16} xl={16} xxl={18}><Card>
                            <DealerTable onSelect={this.onSelectDealer} />
                        </Card></Col>
                    </Row>
                </Modal>
            </div>
        );
    }
}

QueryPanel.propTypes = {
    brands: PropTypes.array.isRequired,
    condition: PropTypes.object.isRequired,
    dealers: PropTypes.array.isRequired,
    exportData: PropTypes.func.isRequired,
    loading: PropTypes.bool.isRequired,
    permissions: PropTypes.array.isRequired,
    querySearch: PropTypes.func.isRequired,
    saveDealer: PropTypes.func.isRequired,
    onChange: PropTypes.func.isRequired,
    onClickReset: PropTypes.func.isRequired,
    isDealerUser: PropTypes.bool,
};

import {connect} from 'react-redux';
import {
    saveQueryCondition,
    querySearch,
    resetQueryPanel,
    exportData,
    changeDealer
} from './actions';
import selectorFactory from 'Shared/utils/immutableToJsSelectorFactory';
import {createSelector} from 'reselect';
const EMPTY_ARRAY = [];
const getConditions = selectorFactory(['page', 'appState', 'queryCondition']);
const getPermissions = selectorFactory(['page', 'domainData', 'permission', 'data']);
const getisDealerUser = selectorFactory(['page', 'domainData', 'initData', 'isDealerUser']);
const getDelears = selectorFactory(['page', 'domainData', 'initData', 'dealers']);

const getBrands = createSelector(
    state => state.getIn(['page', 'domainData', 'initData', 'brands']),
    data => {
        const brands = data.toJS();
        return brands
            ? brands.map(item => ({
                value: item.id,
                text: `(${item.code})${item.name}`
            }))
            : EMPTY_ARRAY;
    }
);

const mapStateToProps = state => ({
    permissions: getPermissions(state),
    condition: getConditions(state),
    loading: state.getIn((['page', 'domainData', 'list', 'isFetching'])),
    brands: getBrands(state),
    dealers: getDelears(state),
    isDealerUser: getisDealerUser(state)
});

const mapDispatchToProps = dispatch => ({
    onChange: (name, value) => dispatch(saveQueryCondition(name, value)),
    querySearch: () => dispatch(querySearch()),
    onClickReset: () => dispatch(resetQueryPanel()),
    exportData: () => dispatch(exportData()),
    saveDealer: data => dispatch(changeDealer(data)),
});

export default connect(mapStateToProps, mapDispatchToProps)(injectIntl(QueryPanel));
